﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CarParkBooking.DAL;
using CarParkBooking.Models;
using System.Globalization;

namespace CarParkBooking.Controllers
{
    public class HomeController : Controller
    {
        CarParkDataContext _dataContext = new CarParkDataContext();
        IList<string> _colorCodes = new List<string> { "#BFBFBF", "#FF6633", "#FF8080", "#FFCC99", "#FFD320", "#CCFFFF"
            , "#83CAFF", "#00B8FF", "#0099FF" };

        public ActionResult Index()
        {
            ViewBag.Message = "Modify this template to jump-start your ASP.NET MVC application.";

            return View();
        }

        public ActionResult CarPark(int? SelectedCarParkId, string SelectedDate)
        {
            DateTime selectedMonth;
            if (String.IsNullOrEmpty(SelectedDate))
            {
                selectedMonth = DateTime.Today;
            }
            else
            {
                selectedMonth = DateTime.ParseExact(SelectedDate, "yyyy_MM_dd", CultureInfo.InvariantCulture);
            }

            ViewBag.SelectedDate = selectedMonth;

            var model = new CarParkBookingModel();

            // get list of Car Park
            model.CarParks = (
                from carpark in _dataContext.CarParks 
                select carpark).ToList();

            foreach (var item in model.CarParks)
            {
                item.Bookings = null;
            }

            // get selected Car Park
            if (SelectedCarParkId == null)
            {
                SelectedCarParkId = model.CarParks.First().ID;
            }
            ViewBag.SelectedCarPark = SelectedCarParkId;
            model.SelectedCarPark = model.CarParks.Where(carpark => carpark.ID == SelectedCarParkId).FirstOrDefault();
            model.SelectedCarPark.Bookings = null;


            // get remaining slot of current user in this month
            var bookedSpacesOfCurrentUserInMonth =
                from b in _dataContext.Bookings
                where b.UserName.Equals(User.Identity.Name)
                select b;
            model.RemainingSlotInMonth = model.SelectedCarPark.MaxSlotPerMonth.Value - bookedSpacesOfCurrentUserInMonth.Count();

            // get selected month
            model.SelectedMonth = selectedMonth;

            // get Color Codes
            model.ColorCodes = this._colorCodes;

            // get Bookings for each day in the selected month
            var bookedSpacesInMonth =
                from b in _dataContext.Bookings
                where b.BookedDate.Value.Year == selectedMonth.Year && b.BookedDate.Value.Month == selectedMonth.Month
                group b by b.BookedDate into g
                select new { Key = g.Key, BookedSpaces = g.ToList() };

            DateTime beginDateOfMonth = new DateTime(selectedMonth.Year, selectedMonth.Month, 1);
            DateTime endDateOfMonth = new DateTime(selectedMonth.Year, selectedMonth.Month,
                DateTime.DaysInMonth(selectedMonth.Year, selectedMonth.Month));
            var bookCalendarModels = new List<BookCalendarModel>();
            for (DateTime currentDate = beginDateOfMonth; currentDate <= endDateOfMonth; currentDate = currentDate.AddDays(1))
            {
                if (currentDate.DayOfWeek == DayOfWeek.Saturday || currentDate.DayOfWeek == DayOfWeek.Sunday)
                {
                    continue;
                }

                BookCalendarModel bookCalendarModel;

                bookCalendarModel = BookCalendarModel.GetModelByCarParkAndBookDate(SelectedCarParkId.Value, currentDate
                    , User.Identity.Name);
                

                bookCalendarModels.Add(bookCalendarModel);
            }

            model.BookCalendarModels = bookCalendarModels;

            return View(model);
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your app description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        [HttpPost]
        public JsonResult GetLatestDataForCellCalendar(int? selectedCarParkId, DateTime selectedDate)
        {
            if (selectedDate == null)
            {
                selectedDate = DateTime.Today;
            }
            else
            {
                selectedDate = new DateTime(selectedDate.Year, selectedDate.Month, selectedDate.Day);
            }

            BookCalendarModel model = BookCalendarModel.GetModelByCarParkAndBookDate(selectedCarParkId.Value , selectedDate, User.Identity.Name);

            var result = new { data = model, status = "ok" };

            return Json(result, JsonRequestBehavior.DenyGet);
        }

        [HttpPost]
        public JsonResult BookCarPark(int? selectedCarParkId, DateTime selectedDate)
        {
            if (selectedDate == null)
            {
                selectedDate = DateTime.Today;
            }
            else
            {
                selectedDate = new DateTime(selectedDate.Year, selectedDate.Month, selectedDate.Day);
            }

            BookCalendarModel model = BookCalendarModel.BookForUser(selectedCarParkId.Value, selectedDate, User.Identity.Name);

            var result = new { data = model, status = "ok" };

            return Json(result, JsonRequestBehavior.DenyGet);
        }

        [HttpPost]
        public JsonResult CancelCarParkBooking(int? selectedCarParkId, DateTime selectedDate)
        {
            if (selectedDate == null)
            {
                selectedDate = DateTime.Today;
            }
            else
            {
                selectedDate = new DateTime(selectedDate.Year, selectedDate.Month, selectedDate.Day);
            }

            BookCalendarModel model = BookCalendarModel.CancelBookingForUser(selectedCarParkId.Value, selectedDate, User.Identity.Name);

            var result = new { data = model, status = "ok" };

            return Json(result, JsonRequestBehavior.DenyGet);
        }

        [HttpPost]
        public JsonResult GetRemaingBookSpacesOfUserInMonth(int selectedCarParkId, string selectedMonth)
        {
            DateTime selectedDate;
            if (string.IsNullOrEmpty(selectedMonth))
            {
                selectedDate = DateTime.Today;
            }
            else
            {
                selectedDate = DateTime.ParseExact(selectedMonth, "yyyy_MM_dd", CultureInfo.InvariantCulture);
            }

            int remaingBookSpacesOfUserInMonth = CarParkBookingModel.GetRemaingBookSpacesOfUserInMonth(selectedCarParkId, User.Identity.Name, selectedDate);

            var result = new { data = remaingBookSpacesOfUserInMonth, status = "ok" };

            return Json(result, JsonRequestBehavior.AllowGet);
        }
    }
}

//DateTimeFormatInfo dtfi = new DateTimeFormatInfo();
//dtfi.ShortDatePattern = "yyyy_MM_dd";
//dtfi.DateSeparator = "_";
//DateTime bookedDate = Convert.ToDateTime(date, dtfi);

//var bookedSpacesPerDay = bookedSpacesInMonth.Where(x => x.Key.Value == currentDate).Select(x => x.BookedSpaces).FirstOrDefault();
//                if (bookedSpacesPerDay == null)
//                {
//                    bookedSpacesPerDay = new List<Booking>();
//                }

//                bookCalendarModel.CanBook = true;
//                bookCalendarModel.BookDate = currentDate;
//                bookCalendarModel.RemainingBookSpaces = model.SelectedCarPark.MaxSlotPerDay.Value - bookedSpacesPerDay.Count();
//                bookCalendarModel.BookedUsers = (from b in bookedSpacesPerDay select b.UserName).ToList();
//                bookCalendarModel.IsBookedByYourself = bookCalendarModel.BookedUsers.Contains(User.Identity.Name);

//                if (bookedSpacesPerDay.Count() == model.SelectedCarPark.MaxSlotPerDay
//                    || bookedSpacesOfCurrentUserInMonth.Where(x => x.BookedDate.Value == currentDate).Count() > 0
//                    || model.SelectedMonth > currentDate)
//                {
//                    bookCalendarModel.CanBook = false;
//                }